package com.mc.fastkit.dialog.animator

import android.view.View
import com.mc.fastkit.ext.getLocationOnScreen
import com.mc.fastkit.ext.screenHeight
import com.mc.fastkit.ext.screenWidth

/**
 * 从锚点View进行缩放、平移的动画
 * @author: MasterChan
 * @date: 2025-03-31 15:44
 */
class FromAnimator(
    private val anchor: View,
    private val offsetX: Float = 0f,
    private val offsetY: Float = 0f,
    private val initScale: Float = 0f
) : AbsDialogAnimator() {

    private var translateX = 0f
    private var translateY = 0f

    override fun init() {
        target!!.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        val anchorPoint = anchor.getLocationOnScreen()
        val anchorCenterX = anchorPoint.x + anchor.width / 2f
        val anchorCenterY = anchorPoint.y + anchor.height / 2f
        val screenCenterX = anchor.context.screenWidth / 2f
        val screenCenterY = anchor.context.screenHeight / 2f

        translateX = screenCenterX - anchorCenterX + offsetX
        translateY = screenCenterY - anchorCenterY + offsetY
        target!!.translationX = -translateX
        target!!.translationY = -translateY
        target!!.scaleX = 0f
        target!!.scaleY = 0f
        target!!.alpha = 0f
    }

    override fun show(onEnd: (() -> Unit)?) {
        target!!.animate()
            .translationX(initScale)
            .translationY(initScale)
            .scaleX(1f)
            .scaleY(1f)
            .alpha(1f)
            .setDuration(duration)
            .withEndAction(onEnd)
            .start()
    }

    override fun dismiss(onEnd: (() -> Unit)?) {
        target!!.animate()
            .translationX(-translateX)
            .translationY(-translateY)
            .scaleX(initScale)
            .scaleY(initScale)
            .alpha(0f)
            .setDuration(duration)
            .withEndAction(onEnd)
            .start()
    }
}